package com.sportwise.utils;

import java.io.IOException;
import java.io.StringWriter;

import org.codehaus.jackson.map.ObjectMapper;

public class JSONUtils {
	private static ObjectMapper defaultMapper = new ObjectMapper();
	
	private JSONUtils() {
		
	}
	/**
     * Converts an object to its JSON representation.
     * 
     * @param o The object to convert.
     * @return The JSON string representation of the specified object.
     */
    public static String toJSON(final Object o) {
        try {
            final StringWriter w = new StringWriter();
            defaultMapper.writeValue(w, o);
            return w.toString();
        } catch (final IOException exn) {
            throw new IllegalStateException(exn);
        }
    }
    
    /**
     * Instantiates an object using its JSON string representation.
     * 
     * @param json The JSON string representation of the class.
     * @param classType The type of object to instantiate.
     * @param <T> Generic used to provide the class type.
     * @return An object instantiated from the specified JSON.
     */
    public static <T> T fromJSON(final String json, final Class<T> classType) {
        try {
            return defaultMapper.readValue(json, classType);
        } catch (final IOException exn) {
            throw new IllegalStateException(exn);
        }
    }
    
    public static ObjectMapper getMapper() {
        return defaultMapper;
    }

}
